import { useState } from 'react'
import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import { PostCard, PostForm } from '../../components/index'
import './index.styl'

export default function Index() {
  const [posts, setPosts] = useState([
    {
      title: '泰罗奥特曼',
      content: '泰罗是奥特之父和奥特之母唯一的亲生儿子。'
    }
  ])
  const [formTitle, setFormTitle] = useState('')
  const [formContent, setFormContent] = useState('')

  function handleSubmit(e) {
    e.preventDefault()
    if (!(formTitle && formContent)) {
      return Taro.showToast({
        title: '请填写信息',
        icon: 'error',
        duration: 2000
      })
    }
    Taro.showToast({
      title: '提交成功',
      icon: 'success',
      duration: 2000
    })
    const newPosts = [...posts, { title: formTitle, content: formContent }]
    setPosts(newPosts)
    setFormTitle('')
    setFormContent('')
  }
  return (
    <View className='index'>
      {posts.map((post, index) => (
        <PostCard
          key={index}
          title={post.title}
          content={post.content}
          isList
        />
      ))}
      <PostForm
        formTitle={formTitle}
        formContent={formContent}
        handleSubmit={e => handleSubmit(e)}
        handleTitleInput={e => setFormTitle(e.target.value)}
        handleContentInput={e => setFormContent(e.detail.value)}
      />
    </View>
  )
}
